#!/usr/bin/perl -w

#
# USAGE:
#   jabber-tool-roster-import <jid> <password> [<host> <port>] [<input-file>]
#

use strict;
use open ":utf8";
use AnyEvent;
use Net::XMPP2::IM::Connection;
use Net::XMPP2::IM::Roster;

binmode STDIN, ":utf8";

my $DEBUG   = 0;  # set to 1 if you want to see a protocol dump
my $TIMEOUT = 600; # timeout the whole program after $TIMEOUT seconds

my ($jid, $pass, $host, $port) = @ARGV;

my $j = AnyEvent->condvar;

my $con;
if(defined $host && defined $port)
{
    $con =
	Net::XMPP2::IM::Connection->new (
    	    jid              => $jid,
    	    password         => $pass,
    	    initial_presence => -5,
    	    override_host => $host,
    	    override_port => $port);
    shift @ARGV;
    shift @ARGV;
    shift @ARGV;
    shift @ARGV;
}
else
{
    $con =
	Net::XMPP2::IM::Connection->new (
    	    jid              => $jid,
    	    password         => $pass,
    	    initial_presence => -5);
    shift @ARGV;
    shift @ARGV;
}

$con->reg_cb (
   debug_recv => sub { print "< $_[1]\n" },
   debug_send => sub { print "> $_[1]\n" },
) if $DEBUG;

my $timer =
   AnyEvent->timer (
      after => 600, cb => sub { warn "got timeout, exiting..."; $j->broadcast }
   );

$main::count = 0;
$main::lines = 0;
@main::LINES = ();

sub my_contact_callback
{
    $main::count++;
    if($main::count == $main::lines)
    {
	$j->broadcast;
    }
    return 1;
}

sub my_add_contact
{
    my $line;
    my $con = shift;
    return if(!defined $con || !defined $con->{roster});

    my $ro = $con->get_roster;
    my $i;

    while(<>)
    {
	$main::lines++;
	chomp;
	if(/\S+/)
	{
	    $main::LINES[$main::lines - 1] = $_;
	}
    }

    foreach $i (@main::LINES)
    {
        if($i =~ /^contact: (.+), name: (.*), groups: (.*), subscription:/)
        {
	    $ro->new_contact($1, $2, $3, sub { &my_contact_callback(@_);});
	}
    }
}

$con->reg_cb (
   session_ready => sub {
      my ($con) = @_;
      &my_add_contact($con);
   },
   error => sub {
      my ($con, $error) = @_;
      warn "error: " . $error->string . "\n";
   },
   disconnect => sub {
      my ($con, $host, $port, $message) = @_;
      warn "disconnected from $host:$port: $message\n";
      $j->broadcast;
   },
);

$con->connect;
$j->wait;

print "$main::count/$main::lines imported\n";
